﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Data.OleDb;

namespace DATN.GroupCustomer
{
    public partial class GroupMM : System.Web.UI.Page
    {
        private string cnnString;
        SqlConnection cnn;
        SqlCommand cmd;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (Session["Us_Id"] != null)
                {
                    btnCreateNew.Visible = false;
                    btnDelete.Visible = false;
                        //Load Dropdownlist:
                        BindDrr();
                }
                else
                {
                    Response.Redirect("../Account/Login.aspx");
                }
                Validate();
            }
        }

        //Bind data to drr:
        protected void BindDrr()
        {
            try
            {
                cnnString = ConfigurationManager.ConnectionStrings["DATNconnection"].ToString();
                cnn = new SqlConnection(cnnString);
                cnn.Open();

                string SearchQuery = "SELECT * FROM dbo.GroupCustomer WHERE Us_Id = @Us_Id";

                cmd = new SqlCommand(SearchQuery, cnn);

                cmd.Parameters.Add("@Us_Id", SqlDbType.Int);
                cmd.Parameters["@Us_Id"].Value = Convert.ToInt16(Session["Us_Id"]);

                SqlDataReader reader = cmd.ExecuteReader();

                //Group Khach hang:
                var GroupCS = new Dictionary<string, string>();
                GroupCS.Add("-1", "Tất Cả");

                int i = 0;
                while (reader.Read())
                {
                    i++;
                    GroupCS.Add(reader["GrCus_Id"].ToString(), reader["Name"].ToString());
                }

                Drr_Group.DataTextField = "Value";
                Drr_Group.DataValueField = "Key";
                Drr_Group.DataSource = GroupCS;
                Drr_Group.DataBind();

                //Check Nếu nhóm Group Rỗng:
                if (i == 0)
                {
                    lb_AddtoGroup.Text = "Bạn Chưa có Nhóm Khách Hàng!<br/> Click vào Tạo Nhóm Ðể Tạo Nhóm khách Hàng";
                    Drr_Group.Visible = false;
                    btnCreateNew.Visible = true;
                    btnDelete.Visible = false;
                    btnMail.Visible = false;
                    btnHienThi.Visible = false;
                    Label1.Visible = false;
                }
                else
                {
                    btnMail.Visible = true;
                    btnHienThi.Visible = true;
                    Label1.Visible = true;
                    Drr_Group.Visible = true;
                    lb_AddtoGroup.Text = "";
                    btnCreateNew.Visible = false;
                }

                cnn.Close();
            }
            catch (Exception ex)
            {
                cnn.Close();
                Response.Write("Lỗi: " + ex);
            }
            finally
            {
                cnn.Close();
            }
        }

        //Tìm những Customer nào thuộc Group được select:
        protected void CustomerId()
        {
            try
            {
                cnnString = ConfigurationManager.ConnectionStrings["DATNconnection"].ToString();
                cnn = new SqlConnection(cnnString);
                cnn.Open();

                string SearchQuery = "SELECT * FROM dbo.GroupCs WHERE GrCus_Id = @GrCus_Id ";

                cmd = new SqlCommand(SearchQuery, cnn);

                cmd.Parameters.Add("@GrCus_Id", SqlDbType.Int);
                cmd.Parameters["@GrCus_Id"].Value = Convert.ToInt16(Drr_Group.SelectedValue);

                SqlDataReader reader = cmd.ExecuteReader();

                string CkCusID ="";
                int i = 0;
                while (reader.Read())
                {
                    i++;
                   CkCusID += reader["Cus_Id"].ToString() + " ";
                }

                if (i == 0)
                {
                    lb_AddtoGroup.Text = "Chưa có khách hàng nào trong nhóm! ";
                 
                }
                else
                {
                    lb_AddtoGroup.Text = "";
                    BindDatatoGridView(CkCusID);
                }

                cnn.Close();
            }
            catch (Exception ex)
            {
                cnn.Close();
                Response.Write("Lỗi hiển thị: " + ex);
            }
            finally
            {
                cnn.Close();
            }
        }

        //Bind Data vào Gridview:
        protected void BindDatatoGridView(string a)
        {  
            string[] words = a.Split(' ');
            string queryCus = "";

            for (int i = 0; i < (words.Length - 1); i++)
            {
                if (i == 0)
                {
                        queryCus += " AND Cus_Id = " + words[i];
                }
                else
                {
                        queryCus += " OR Cus_Id = " + words[i];
                }
            }

            try
            {
                cnnString = ConfigurationManager.ConnectionStrings["DATNconnection"].ToString();
                cnn = new SqlConnection(cnnString);
                cnn.Open();

                string SearchQuery = "SELECT * FROM dbo.Customers WHERE 1 = 1"
                                     + queryCus;

                //Response.Write(SearchQuery);
                SqlCommand cmd = new SqlCommand(SearchQuery, cnn);
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                DataSet ds = new DataSet();
                da.Fill(ds);

                DataView dv;
                dv = new DataView(ds.Tables[0]);

                if (ds.Tables.Count > 0)
                {
                    if (ds.Tables[0].Rows.Count > 0)
                    {
                        gvCheckboxes.DataSource = dv;
                        gvCheckboxes.DataBind();
                        btnDelete.Visible = true;
                    }
                    else
                    {
                        lb_AddtoGroup.Text = "Không có dữ liệu về bảng này!";
                    }
                }
                else
                {
                    lb_AddtoGroup.Text = "Không kết nối được đến database.";
                }
            }
            catch (Exception ex)
            {
                cnn.Close();
                Response.Write("Lỗi hiển thị gridview: " + ex);
            }
            finally
            {
                cnn.Close();
            }
        }

        //Click vào button Hiển Thị:
        protected void btnHienThi_Click(object sender, EventArgs e)
        {
            gvCheckboxes.DataSource = null;
            gvCheckboxes.DataBind();
            if (Drr_Group.SelectedValue != "-1")
            {
                CustomerId();
            }
            else
            {
                Response.Write("tất cả" + Drr_Group.SelectedValue);
            }
        }

        //Xóa button
        protected void btnDelete_Click(object sender, EventArgs e)
        {
            gvCheckboxes.DataSource = null;
            gvCheckboxes.DataBind();
            if (Drr_Group.SelectedValue != "-1")
            {
                string[] IDs = hdnFldSelectedValues.Value.Trim().Split('|');

                //string CustomerGroup = "";
                try
                {
                    int ba = Convert.ToInt16(IDs[0]);
                    for (int i = 0; i < IDs.Length; i++)
                    {
                        DelCus(IDs[i]);
                    }

                    gvCheckboxes.DataSource = null;
                    gvCheckboxes.DataBind();
                    if (Drr_Group.SelectedValue != "-1")
                    {
                        CustomerId();
                    }
                    else
                    {
                        Response.Write("tất cả" + Drr_Group.SelectedValue);
                    }

                }
                catch (Exception ex)
                {
                    lb_AddtoGroup.Text = "Bạn Chưa chọn Khách Hàng Nào cả!";
                }
            }
            else
            {
                Response.Write("tất cả" + Drr_Group.SelectedValue);
            }
        }

      
        //Xóa Customers trong Group.
        protected void DelCus(string cus_id)
        {
            int Cus = Convert.ToInt16(cus_id);
            try
            {
                cnnString = ConfigurationManager.ConnectionStrings["DATNconnection"].ToString();
                cnn = new SqlConnection(cnnString);
                cnn.Open();
                cmd = cnn.CreateCommand();

                cmd = cnn.CreateCommand();
                cmd.CommandText = "DELETE FROM [dbo].[GroupCs] "
                                 +" WHERE Cus_Id = @Cus_Id AND GrCus_Id = @GrCus_Id";

                cmd.Parameters.Add("@Cus_Id", SqlDbType.Int);
                cmd.Parameters["@Cus_Id"].Value = Cus;

                cmd.Parameters.Add("@GrCus_Id", SqlDbType.Int);
                cmd.Parameters["@GrCus_Id"].Value = Convert.ToInt16(Drr_Group.SelectedValue);
                cmd.ExecuteNonQuery();

                //Response.Write("Thành Công!");
                cnn.Close();
            }
            catch (Exception ex)
            {
                Response.Write(ex);
                cnn.Close();
            } 
            
        }

        //Tạo Mới Group Button
        protected void btnCreateNew_Click(object sender, EventArgs e)
        {
            Response.Redirect("../GroupMM/CreateGroup.aspx");
        }

        //Trong GridView
        protected void gvCheckboxes_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow && (e.Row.RowState == DataControlRowState.Normal || e.Row.RowState == DataControlRowState.Alternate))
            {
                CheckBox chkBxSelect = (CheckBox)e.Row.Cells[0].FindControl("chkBxSelect");
                CheckBox chkBxHeader = (CheckBox)this.gvCheckboxes.HeaderRow.FindControl("chkBxHeader");
                HiddenField hdnFldId = (HiddenField)e.Row.Cells[0].FindControl("hdnFldId");

                chkBxSelect.Attributes["onclick"] = string.Format("javascript:ChildClick(this,document.getElementById('{0}'),'{1}');", chkBxHeader.ClientID, hdnFldId.Value.Trim());
            }
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                DataRowView row = e.Row.DataItem as DataRowView;

                // Hiển thị cho column Giới Tính
                Label Lb_Sex = e.Row.FindControl("Lb_Sex") as Label;
                if (Lb_Sex != null)
                {
                    if (row["Sex"].ToString() == "1")
                    {
                        Lb_Sex.Text = "Nam";
                    }
                    if (row["Sex"].ToString() == "2")
                    {
                        Lb_Sex.Text = "Nữ";
                    }
                    if (row["Sex"].ToString() == "3")
                    {
                        Lb_Sex.Text = "Khác";
                    }
                }
            }
        }

        protected void btnMail_Click(object sender, EventArgs e)
        {
            if (Drr_Group.SelectedValue != "-1")
            {
                string[] IDs = hdnFldSelectedValues.Value.Trim().Split('|');

                //string CustomerGroup = "";
                if (IDs.Length > 1)
                {
                    for (int i = 0; i < IDs.Length; i++)
                    {
                        DelCus(IDs[i]);
                    }
                    if (Drr_Group.SelectedValue != "-1")
                    {
                        CustomerId();
                    }
                    else
                    {
                        Response.Write("tất cả" + Drr_Group.SelectedValue);
                    }
                }
                else
                {
                   
                }
            }
            else
            {
                Response.Write("tất cả" + Drr_Group.SelectedValue);
            }
        }

    }
}